import os
import time
import subprocess
import json

# Load configuration
CONFIG_FILE = "config.json"
with open(CONFIG_FILE, "r") as file:
    config = json.load(file)

HOST_IP = config["host_ip"]
VIRTUAL_IP = config["virtual_ip"]
CHECK_INTERVAL = config["ping_interval"]
INTERFACE = config["interface"]
IS_STANDBY = config["is_standby"]

# Function to assign VIP
def assign_vip():
    try:
        subprocess.run(f"netsh interface ip add address \"{INTERFACE}\" {VIRTUAL_IP} 255.255.255.0", check=True, shell=True)
        print(f"Assigned VIP {VIRTUAL_IP}")
    except subprocess.CalledProcessError as e:
        print(f"Error assigning VIP: {e}")

# Function to remove VIP
def remove_vip():
    try:
        subprocess.run(f"netsh interface ip delete address \"{INTERFACE}\" {VIRTUAL_IP}", check=True, shell=True)
        print(f"Removed VIP {VIRTUAL_IP}")
    except subprocess.CalledProcessError as e:
        print(f"Error removing VIP: {e}")

# Function to check if the host is alive
def is_host_alive():
    response = subprocess.run(f"ping -n 1 {HOST_IP}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if "unreachable" in f"{response.stdout.lower()}" or "timed out" in f"{response.stdout.lower()}":
        return False
    return response.returncode == 0

# Standby server logic
def standby_server():
    vip_assigned = False
    while True:
        if is_host_alive():
            print("Host is online.")
            if vip_assigned:
                print("Releasing VIP as host is active.")
                remove_vip()
                vip_assigned = False
        else:
            print("Host is down.")
            if not vip_assigned:
                print("Taking over VIP.")
                assign_vip()
                vip_assigned = True
        time.sleep(CHECK_INTERVAL)

# Host server logic
def host_server():
    while True:
        if not is_host_alive():
            print("Host is offline, ensuring VIP is released.")
            remove_vip()
        else:
            print("Host is online, ensuring VIP is active.")
            assign_vip()
        time.sleep(CHECK_INTERVAL)

# Main entry point
if __name__ == "__main__":
    is_standby = IS_STANDBY  # Set to True for standby, False for host
    if is_standby:
        standby_server()
    else:
        host_server()